package com.sinosoft.builder.config;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

import org.apache.maven.plugin.logging.Log;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.types.FileSet;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

import com.sinosoft.builder.generator.GeneratorException;

public class FileHelper {

	/**
	 * 从指定目录复制资源到目标目录
	 * 
	 * @param fromDir
	 * @param toDir
	 */
	public static void copyResources(File fromDir, File toDir, Log log) {
		log.info("复制" + fromDir.getPath() + "到" + toDir.getPath());
		Copy copy = new Copy();
		Project project = new Project();
		project.init();
		copy.setProject(project);
		copy.setTaskName("copy");
		copy.setTodir(toDir);
		if (fromDir.isDirectory()) {
			FileSet fileSet = new FileSet();
			fileSet.setDir(fromDir);
			copy.addFileset(fileSet);
		} else if (fromDir.isFile()) {
			copy.setFile(fromDir);
		}

		copy.execute();
	}

	/**
	 * 创建文件
	 * 
	 * @param context
	 * @param javaFile
	 * @throws GeneratorException
	 */
	public static void generatorFile(VelocityContext context, Template temp,
			File javaFile) throws GeneratorException {
		File javaDir = javaFile.getParentFile();
		if (!javaDir.exists()) {
			javaDir.mkdirs();
		}
		try {
			if (javaFile.exists()) {
				javaFile.delete();
			}
			Writer out = new BufferedWriter(new FileWriter(javaFile));
			temp.merge(context, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			throw new GeneratorException("创建实体出现错误：" + javaFile.getName(), e);
		}
	}

}
